"use strict";

const babel = require("@babel/core");
const path = require("path");
const fs = require("fs");
const babelPluginPath = path.resolve(__dirname, "plugin.js"); // 插件文件地址
const babelConfigPath = path.resolve(__dirname, "babel.config.js"); // babel 配置
const relayFileName = `relayFile.js`; // 中间文件

// JSON文件转换
const handleJsonFile = (jsonFilePath) => {
  const oldContent = fs.readFileSync(jsonFilePath);
  const newContent = "let b=" + oldContent + ";exports.b = b;";
  return newContent;
};
// 更新代码
const updateJson = (code, version, field) => {
  const newContent = babel.transformSync(code, {
    plugins: [[babelPluginPath, { version, field }]],
    filename: babelConfigPath,
  }).code;
  return newContent;
};
// 4-输出文件
const inputResult = (newContent, filePath) => {
  fs.writeFileSync(path.resolve(__dirname, relayFileName), newContent, "utf8");
  const trueInfo = require(`./${relayFileName}`).b;
  fs.writeFileSync(filePath, JSON.stringify(trueInfo), "utf8");
};

class UpgradeVersion {
  constructor() {}
  static apply(jsonFilePath, version, field) {
    const addContent = handleJsonFile(jsonFilePath);
    const newContent = updateJson(addContent, version, field);
    inputResult(newContent, jsonFilePath);
  }
}

module.exports = UpgradeVersion;
